<script lang="jsx">
import { buttonKeys, formatData, mergeVModel } from './utils'
import FuncBtn from './FuncBtn.vue'
import ExcelExport from '@/components/ExcelExport/index.vue'
import request from '@/utils/request'

export default {
  name: 'CrudTableHeader',
  components: { FuncBtn, ExcelExport },
  props: {
    loading: Boolean,
    config: {
      type: Object,
      default: () => ({})
    },
    list: Array,
  },
  inject: ['size', 'add', 'exportExcel', 'columns'],
  data() {
    return {
      form: {},
      showForm: false,
      isExporting: false
    }
  },
  created() {
    const { formatter, drfaultProps } = this.config
    if (formatter) this.formatter = formatter
    // console.log(formatter)
    if(drfaultProps) {
      this.form = {...drfaultProps}
      this.onClickQuery()
    }
  },
  methods: {
    getFormData() {
      // 第三个参数是，是否删除源字段
      return formatData(this.form, this.formatter, true)
    },
    async onClickExportExcel() {
      let notice = null
      try {
        await this.$confirm('确定导出数据吗？', '系统提示', {
          type: 'info'
        })
        this.isExporting = true
        notice = this.$notify({
          iconClass: 'el-icon-loading',
          title: '导出提示',
          showClose: false,
          position: 'bottom-right',
          offset: 80,
          duration: 0,
          message: '数据导出中,请稍后……'
        })
        const postData = formatData(this.form, this.formatter, true)
        const reqBody = {
          method: 'post',
          responseType: 'blob'
        }
        const { fileName = '导出信息', params, ...args } = this['exportExcel']
        if (params) Object.assign(postData, params)
        Object.assign(reqBody, args)
        reqBody.data = postData

        const binaryData = await request(reqBody)
        const blob = new Blob([binaryData], { type: 'application/octet-stream' })
        if ('download' in document.createElement('a')) {
          const downloadElement = document.createElement('a')
          const href = window.URL.createObjectURL(blob) // 创建下载的链接
          downloadElement.href = href
          downloadElement.download = fileName + '.xlsx' // 下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() // 点击下载
          document.body.removeChild(downloadElement) // 下载完成移除元素
          window.URL.revokeObjectURL(href) // 释放掉blob对象
        } else {
          navigator.msSaveBlob(blob, fileName + '.xlsx')
        }
      } catch (error) {
        console.info('CrudTable Export【catch】', error)
      } finally {
        this.isExporting = false
        if (notice != null) notice.close()
      }
    },
    onClickAdd() {
      this.$emit('add')
    },
    onClickClear() {
      this.$refs.form?.resetFields()
      this.form = {}
    },
    onClickReset() {
      this.showForm = false
      this.onClickClear()
      this.$emit('reset')
    },
    onClickQuery() {
      this.$emit('query', this.getFormData())
    }
  },
  render() {
    const { add, exportExcel, size, list, columns } = this
    const { insideExport = true, fileName = '' } = exportExcel || {}
    const { collapse = true } = this.config

    const { searchForm: searchFormSlots, action: actionSlots } = this.$scopedSlots
    const formNodes = searchFormSlots && mergeVModel(searchFormSlots(), this.form)
    const actionNodes = actionSlots && actionSlots()

    if (collapse) {
      return (
        <div class='crud-table--header'>
          {
            searchFormSlots && (
              <ElButton
                size={size}
                icon={this.showForm ? 'el-icon-circle-close' : 'el-icon-search'}
                type={this.showForm ? 'default' :'primary'}
                onClick={() => this.showForm = !this.showForm}
              >
                { this.showForm ? '隐藏' : '查询' }
              </ElButton>
            )
          }
          <FuncBtn config={add} func={buttonKeys.ADD} onClick={this.onClickAdd} />
          { actionNodes }
          {
            exportExcel && insideExport
              ? (<ExcelExport style='margin-left: 10px;' disabled={list.length === 0} table-thead={columns} list={list} size={size} fileName={fileName} />)
              : (<FuncBtn
                config={exportExcel}
                func={buttonKeys.EXPORT_EXCEL}
                disabled={this.loading}
                loading={this.isExporting}
                onClick={this.onClickExportExcel}
              />)
          }
          {
            searchFormSlots && (
              <transition name='slider-in-top' mode='out-in'>
                <ElForm v-show={this.showForm} ref='form' inline size={size}>
                  { formNodes }
                  <ElFormItem >
                    <ElButton type='default' onClick={this.onClickReset}>重置</ElButton>
                    <ElButton type='info' onClick={this.onClickClear}>清空</ElButton>
                    <ElButton type='primary' icon="el-icon-search" onClick={this.onClickQuery}>查询</ElButton>
                  </ElFormItem>
                </ElForm>
              </transition>
            )
          }
        </div>
      )
    } else {
      return (
        <div className='crud-table--header'>

          <ElForm ref='form' inline size={size}>
            { formNodes }
            <ElFormItem style={ {width: '100%'} } class="my-form-item" >
              {
                searchFormSlots && (
                  <ElButton type='primary' onClick={this.onClickQuery} icon='el-icon-search'>查询</ElButton>
                )
              }
              <FuncBtn config={add} func={buttonKeys.ADD} onClick={this.onClickAdd} />
              { actionNodes }
              {
                exportExcel && insideExport
                  ? (<ExcelExport style='margin-left: 10px;' disabled={list.length === 0} table-thead={columns} list={list} size={size} fileName={fileName} />)
                  : (<FuncBtn
                    config={exportExcel}
                    func={buttonKeys.EXPORT_EXCEL}
                    disabled={this.loading}
                    loading={this.isExporting}
                    onClick={this.onClickExportExcel}
                  />)
              }

            </ElFormItem>
          </ElForm>

        </div>
      )
    }
  }
}
</script>

<style lang="scss" scoped>
  .action-button {
    border: 1px solid #1890ff;
    height: 32px ;
  }
  .right-action {
    float: right;
    display: flex;
    align-items: center;
  }
  .crud-table--header {
    //display: flex;
    //align-items: center;
    //flex-direction: column;
    .el-form {
      padding-top: 18px;
      box-sizing: border-box;

    }
  }
  .my-form-item ::v-deep .el-form-item__content{
    width: 100%;
  }
</style>